﻿
using System.Collections.Generic;

using Irony.Compiler;

namespace IronLua.Ast {

	public class IfStatement : Statement {

		readonly Expression condition;
		readonly BlockStatement then;
		readonly ElseIfList elsifs = new ElseIfList ();
		readonly BlockStatement els;

		public Expression Condition {
			get { return condition; }
		}

		public BlockStatement Then {
			get { return then; }
		}

		public ElseIfList ElseIfs {
			get { return elsifs; }
		}

		public BlockStatement Else {
			get { return els; }
		}

		public override LuaNodeType NodeType {
			get { return LuaNodeType.IfStatement; }
		}

		public IfStatement (CompilerContext context, NonTerminal nonTerminal, SourceLocation location, AstNodeList childNodes)
			: base (context, nonTerminal, location, childNodes)
		{
			condition = childNodes [1].ToExpression ();
			then = childNodes [3].To<BlockStatement> ();
			elsifs.AddRange (CollectElseIfs ());
			if (childNodes [5] != null)
				els = childNodes [5].ChildNodes [1].To<BlockStatement> ();
		}

		IEnumerable<ElseIfClause> CollectElseIfs ()
		{
			foreach (var node in ChildNodes [4].ChildNodes)
				yield return node.To<ElseIfClause> ();
		}

		public override void Accept (ILuaAstVisitor visitor)
		{
			visitor.VisitIfStatement (this);
		}
	}
}
